package com.chunxiadong.config;

import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;

/**
 * @auther QiuShangcheng
 * @create 2021/6/6
 */
@Configuration
public class ShiroConfig {

    /*3.创建shiro过滤器bean，ShiroFilterFactoryBean*/
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("defaultWebSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        //设置安全管理器
        bean.setSecurityManager(defaultWebSecurityManager);

        bean.setLoginUrl("/user/toLogin");//注入未登陆的跳转
        bean.setUnauthorizedUrl("/user/unauthorized");//注入未授权的访问
        bean.setSuccessUrl("/user/loginSuccess");//注入成功后的访问

        //权限设置
//        anon:无需认证就可以访问    authc:必须认证了才能让问
//        user:必须拥有记住我功能才能用     perms :拥有对某个资源的权限才能访问;role:拥有某个角色权限才能访问
        LinkedHashMap<String, String> filterMap = new LinkedHashMap<>();
        filterMap.put("/","anon");
        filterMap.put("/user/**","anon");
        filterMap.put("/admin/**","authc");
        filterMap.put("/logout","logout");
        filterMap.put("/*","authc");

        bean.setFilterChainDefinitionMap(filterMap);
        return bean;
    }

    /*2.创建安全管理器defaultWebSecurityManager*/
    @Bean(name = "defaultWebSecurityManager")
    public DefaultWebSecurityManager defaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //管理userRealm
        securityManager.setRealm(userRealm);
        return securityManager;
    }

    /*1.创建realm的对象*/
    @Bean(name = "userRealm")
    public UserRealm userRealm() {
        return new UserRealm();
    }
}
